const {
  app,
  BrowserWindow,
  screen,
  dialog,
  shell,
  ipcMain,
  session,
} = require("electron");
const path = require("path");
const https = require("https");
const fs = require("fs");

let newWindow = null;
let mainWindow = null;
// 获取文件名
function generateUniqueFileName(folderPath, fileName) {
  const fileExt = path.extname(fileName);
  const fileBasename = path.basename(fileName, fileExt);

  let uniqueFileName = fileName;
  let counter = 1;

  while (fs.existsSync(path.join(folderPath, uniqueFileName))) {
    uniqueFileName = `${fileBasename}_${counter}${fileExt}`;
    counter++;
  }

  return uniqueFileName;
}

const createWindow = () => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;

  mainWindow = new BrowserWindow({
    width: width,
    height: height,
    autoHideMenuBar: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: true,
      preload: path.join(__dirname, "preload.js"),
    },
  });

  let isFirstDownload = true;
  let downloadPath = "";
  const focusedWindow = BrowserWindow.getFocusedWindow();
  // 监听 will-download 事件
  session.defaultSession.on("will-download", (event, item, webContents) => {
    if (isFirstDownload) {
      const options = {
        title: "选择下载位置",
        buttonLabel: "选择",
        properties: ["openDirectory"],
      };
      const result = dialog.showOpenDialogSync(focusedWindow, options);
      if (result && result.length > 0) {
        downloadPath = result[0];
      } else {
        event.preventDefault();
        return;
      }
      isFirstDownload = false;
    }

    // 获取要下载的文件名称
    const fileName = item.getFilename();

    // 构建完整的下载路径
    let fullPath =
      downloadPath + "/" + generateUniqueFileName(downloadPath, fileName);
    console.log("fullPath", fullPath);
    // 修改下载路径
    item.setSavePath(fullPath);
  });

  mainWindow.loadURL("https://www.tianjing.site");
  mainWindow.webContents.on("did-navigate", (event, url) => {
    if (url.indexOf("/page/login.html") > -1) {
      if (newWindow && !newWindow.isDestroyed()) {
        newWindow.close();
        newWindow = null;
      }
    }
  });
  mainWindow.webContents.on("did-navigate-in-page", (event, url) => {
    if (url.indexOf("/page/video_tool.html") > -1) {
      if (newWindow && !newWindow.isDestroyed()) {
        return;
      }
      newWindow = new BrowserWindow({
        width: 1400,
        height: height,
        autoHideMenuBar: true,
        webPreferences: {
          nodeIntegration: true,
          webSecurity: false,
          contextIsolation: true,
          preload: path.join(__dirname, "preload.js"),
          webviewTag: true,
        },
      });
      if (!app.isPackaged) {
        newWindow.loadURL("http://localhost:5173");
        newWindow.webContents.openDevTools();
      } else {
        newWindow.loadURL(`file://${__dirname}/../dist/index.html`);
      }
      newWindow.webContents.session.webRequest.onHeadersReceived(
        (details, callback) => {
          if (
            !(
              details.url.includes("neibu.bingdou") ||
              details.url.includes("qianniu.bingdou") ||
              details.url.includes("www.tianjing.")
            )
          ) {
            details.responseHeaders["Cross-Origin-Opener-Policy"] = [
              "same-origin",
            ];
            details.responseHeaders["Cross-Origin-Embedder-Policy"] = [
              "require-corp",
            ];
          }
          callback({ responseHeaders: details.responseHeaders });
        }
      );
    }
  });
  mainWindow.on("closed", () => {
    // 关闭主窗口时关闭新建窗口
    if (newWindow && !newWindow.isDestroyed()) {
      newWindow.close();
    }
  });
};

app.whenReady().then(async () => {
  await checkForUpdates();
  createWindow();
  ipcMain.handle("send_storage", async () => {
    const localStorageData = await mainWindow.webContents.executeJavaScript(
      `JSON.stringify(localStorage);`
    );
    return localStorageData;
  });
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});

async function checkForUpdates() {
  const localVersion = 11; // 本地版本号

  const postData = JSON.stringify({
    version: localVersion,
  });

  const options = {
    hostname: "qianniu.bingdou.site",
    port: 443,
    path: "/v1/client/version/check",
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Content-Length": Buffer.byteLength(postData),
    },
  };

  try {
    const responseData = await makePostRequest(options, postData);
    const response = JSON.parse(responseData);
    const { force_update, url } = response.data;
    if (force_update === 1) {
      const buttonIndex = dialog.showMessageBoxSync({
        type: "info",
        title: "更新",
        message: "请前往下载最新版本",
        buttons: ["确定"],
      });
      if (buttonIndex === 0) {
        shell.openExternal(url);
        app.quit();
      }
    }
  } catch (err) {
    console.error("Failed to make the request or parse response:", err);
  }
}

function makePostRequest(options, postData) {
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      let data = "";

      res.on("data", (chunk) => {
        data += chunk;
      });

      res.on("end", () => {
        resolve(data);
      });
    });

    req.on("error", (error) => {
      reject(error);
    });

    req.write(postData);
    req.end();
  });
}

const util = require("util");
const pipeline = util.promisify(require("stream").pipeline);
ipcMain.handle("download-video", async (event, videoUrl) => {
  console.log("videoUrl", videoUrl);
  // 解析视频 URL
  const url = new URL(videoUrl);

  // 获取文件名
  const fileName = path.basename(url.pathname);

  console.log("fileName", fileName);
  // 获取桌面路径
  const desktopPath = app.getPath("desktop");

  // 创建文件夹
  const folderPath = path.join(desktopPath, "videos");
  if (!fs.existsSync(folderPath)) {
    fs.mkdirSync(folderPath, { recursive: true });
  }

  // 生成视频文件路径
  const videoPath = path.join(folderPath, url.pathname.replace(/\//g, ''));

  // 发送 HTTPS 请求下载视频
  const response = await new Promise((resolve, reject) => {
    https
      .get(videoUrl, (response) => {
        resolve(response);
      })
      .on("error", (error) => {
        reject(error);
      });
  });

  // 创建可写流
  const fileStream = fs.createWriteStream(videoPath);

  // 使用 pipeline 方法将 response 管道到 fileStream
  await pipeline(response, fileStream);

  return new Promise((resolve) => {
    resolve(videoPath);
  });
});


ipcMain.on("rmdir", () => {
  const desktopPath = app.getPath("desktop");
  const folderPath = path.join(desktopPath, "videos");
  if (fs.existsSync(folderPath)) {
    fs.rmdir(folderPath, { recursive: true }, (err) => {
      if (err) {
        console.error("Error:", err);
        return;
      }
      console.log("Folder deleted successfully");
    });
  }
});

ipcMain.handle("local-video", async (event, buffer, fileName, filePath) => {
  console.log('filePath',filePath)
  const buffer_data = Buffer.from(buffer);
  if (filePath) {
    fs.writeFile(`${filePath}/${fileName}`, buffer_data, (err) => {
      if (err) {
        console.error("Error saving file:", err);
        return;
      }
      console.log("File saved successfully!");
    });
    return;
  }
  const focusedWindow = BrowserWindow.getFocusedWindow();
  const result = dialog.showOpenDialogSync(focusedWindow, {
    properties: ["openDirectory"],
  });
  if (result && !result.canceled) {
    const downloadPath = result[0];
    fs.writeFile(`${downloadPath}/${fileName}`, buffer_data, (err) => {
      if (err) {
        console.error("Error saving file:", err);
        return;
      }
      console.log("File saved successfully!");
    });
    return new Promise((resolve) => {
      resolve(downloadPath);
    });
  }
});